package com.cp;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @author ChengPeng
 * @create 2020-05-26 9:50
 */
public class phoneservice {

    public void get(String mobileCode,String userID) throws Exception{
        //调用远程接口对应地址
        URL url = new URL("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo?mobileCode="+mobileCode+
                "&userID="+userID);

        //建立连接设置连接时间和请求方式
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(5000);
        conn.setRequestMethod("GET");

        //结果码为200表明连接成功且取到返回值
        if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
            InputStream is = conn.getInputStream();
            //内存流
            ByteArrayOutputStream boas = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len =  -1;
            while((len=is.read(buffer))!= -1){
                boas.write(buffer,0,len);
            }
            System.out.println("GET请求获取的数据：" + boas.toString());
            boas.close();
            is.close();

        }
    }

    //post请求，通过http-client来模拟实现http请求
    public void post(String mobileCode,String userID)throws Exception{
        /**HttpClient访问网络的实现步骤：
         *  1. 准备一个请求客户端:浏览器
         *  2. 准备请求方式： GET 、POST
         *  3. 设置要传递的参数
         *  4.执行请求
         *  5. 获取结果
         */
        HttpClient client=new HttpClient();
        PostMethod postMethod=new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx/getMobileCodeInfo");
        //3.设置请求参数
        postMethod.setParameter("mobileCode", mobileCode);
        postMethod.setParameter("userID", userID);
        //4.执行请求 ,结果码
        int code=client.executeMethod(postMethod);
        //5. 获取结果
        String result=postMethod.getResponseBodyAsString();
        System.out.println("Post请求的结果："+result);
    }

    public void soap() throws Exception{

        HttpClient client=new HttpClient();
        PostMethod postMethod=new PostMethod("http://ws.webxml.com.cn/WebServices/MobileCodeWS.asmx");
        //3.设置请求参数
        postMethod.setRequestBody(new FileInputStream("e:/soap.xml"));
        //修改请求的头部
        postMethod.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
        //4.执行请求 ,结果码
        int code=client.executeMethod(postMethod);
        System.out.println("结果码:"+code);
        //5. 获取结果
        String result=postMethod.getResponseBodyAsString();
        System.out.println("Post请求的结果："+result);
    }

    public static void main(String[] args) throws Exception {
        phoneservice ps = new phoneservice();
        //ps.get("18709825268", " ");
        ps.post("18895309589"," ");
        //ps.soap();
    }
}

